#!/usr/bin/envpython
# -*-coding:UTF-8-*-
'''
@File    :   filelock_hple.py
@Contact :   308711822@qq.com
@License :   (C) Copyright 2021-2225, Personal exclusive right.

@Modify Time      @Author    @Version    @Desciption
------------      -------    --------    -----------
2023/6/9 9:51   小钟同学      1.0         None
'''
import os
import fcntl

class SafeRandom:
   def __init__(self):
       self.file = open('/dev/urandom', 'rb')

   def __del__(self):
       self.file.close()

   def get_bytes(self, num_bytes):
       if os.name == 'posix':
           try:
               fcntl.flock(self.file.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
           except IOError:
               raise Exception("Couldn't acquire lock on /dev/urandom")
       return self.file.read(num_bytes)


def generate_token(num_bytes=16):
   rand = SafeRandom()
   return rand.get_bytes(num_bytes).hex()